package command.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;
import server.ClientThread;
import server.Server;

public class AcceptInvitationServer implements CommandServer {

    private String conversationID;
    private ArrayList<User> usersActive;
    private boolean isAcceptConversation = false;

    public AcceptInvitationServer() {
    }

    public void setConversationID(String idOfConversation) {
        conversationID = idOfConversation;
    }

    public void setUserActive(ArrayList<User> usersActiveOfConversation) {
        usersActive = usersActiveOfConversation;
    }

    public void setIsAcceptConversation() {
        isAcceptConversation = true;
    }

    @Override
    public void execute(ClientThread clientThread) {
        try {
            if (!isAcceptConversation) {
                MessageCommunication message = (MessageCommunication) clientThread.getObjectInputStream().
                        readObject();
                User u = (User) clientThread.getObjectInputStream().readObject();
                Server.addUserAtConversation(message.getMessage(), u);
            } else {
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "acceptinvitationclient"));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(new MessageCommunication(true, conversationID));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(usersActive);
                clientThread.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(AcceptInvitationServer.class.getName()).log(Level.SEVERE,
                    "Fallo en la ejecución del comando de aceptar invitación en el cliente", ex);
        }
    }
}
